package ru.niir.goodfil;

import ru.niir.goodfil.utils.SMTPAuthenticator;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.util.Properties;

public class Messager {
    public static void sendEmailWithAttachment(String smtpHost, String port, String username, String password, String email, String caption, String body, String attachmentFile, String fileName) throws MessagingException {
        Properties props = new Properties();
        props.put("mail.smtp.host", smtpHost);
        props.put("mail.smtp.port", port);
        //props.put("mail.smtp.auth", "true");
        //props.put("mail.smtp.starttls.enable", "true");
        //props.put("mail.debug", "true");

        Session session = Session.getInstance(props, new SMTPAuthenticator(username, password));
        String[] emails = email.split(";");
        for (String em : emails) {
            em = em.trim();
            if (em.equals("")) {
                continue;
            }

            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(username));
            message.setSubject(caption, "UTF-8");

            Multipart multipart = new MimeMultipart();

            MimeBodyPart messageBodyPart = new MimeBodyPart();
            messageBodyPart.setText(body, "UTF-8", "html");
            multipart.addBodyPart(messageBodyPart);

            messageBodyPart = new MimeBodyPart();

            DataSource source = new FileDataSource(attachmentFile);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName(fileName);
            multipart.addBodyPart(messageBodyPart);
            message.setContent(multipart);
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(em));

            Transport.send(message);
        }
    }
}
